import { useState, useEffect, useContext } from 'react';
import { NavBar, Tabs, List, Badge, Grid, Toast, InfiniteScroll, ActionSheet } from 'antd-mobile';
import { MoreOutline } from 'antd-mobile-icons';
import moment from 'moment';
import { useHistory, useRouteMatch } from "react-router-dom";
import { DeleteOutlined } from '@ant-design/icons';

import AvatarImage from '../../../components/AvatarImage';

import { renderMsgBrief } from '../../../utils';
import { MsgTypeMap } from '../../../constants';
import { MySdkStoreContext } from '../../../context';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const myUserId = mySdkStore.mockConfig.userId;
  const { params: { defaultActiveKey } } = useRouteMatch();

  const [messageList, setMessageList] = useState([]);
  const [pagination, setPagination] = useState({ currentCursorId: undefined, nextCursorId: undefined });
  const [tabKey, setTabKey] = useState(defaultActiveKey || 'all');
  const [moreOperationVisible, setMoreOperationVisible] = useState(false);
  const [currentOperationItem, setCurrentOperationItem] = useState();
  const [hasMore, setHasMore] = useState(false);

  const getNextData = async (cursorId, { changeTab } = { changeTab: false}) => {
    const apiMap = {
      'all': 'queryAllDingMessages',
      'send': 'querySentDingMessages',
      'unread': 'queryUnReadDingMessages',
    };
    const api = apiMap[tabKey] || 'queryAtMeMessage';
    const res  = await mySdkStore.sdk[api]({ cursorId, userId: myUserId });
    const { next, list, rows } = res;
    const newList = cursorId ? list || rows || [] : [];
    setMessageList(changeTab? newList : [...messageList, ...newList]);
    setPagination({ currentCursorId: cursorId, nextCursorId: next });
    setHasMore(next);
  }

  useEffect(() => {
    getNextData(undefined, { changeTab: true });
  }, [tabKey]);

  const handleChange = (tabKey) => {
    setTabKey(tabKey);
  }

  const handlePassed = (message?: { cid: string; messageId: string}) => {
    if (!message) {
      // 全部处理
      mySdkStore.sdk.closeAllMessageDealLater().then(() => {
        Toast.show('所有消息已处理');
        getNextData(undefined);
      });
    } else {
      // 单个处理
      mySdkStore.sdk.closeMessageDealLater({ messages: [message]}).then(() => {
        getNextData(pagination.nextCursorId);
      });
    }
  }

  // 是否由我发送
  const isSendByMe = (userId) => {
    return userId === myUserId;
  }

  // 控制“更多”菜单展示开关
  const handleMoreOpeationVisible = (messageData) => {
    setMoreOperationVisible(true);
    setCurrentOperationItem(messageData);
  }

  // 点击”删除“事件
  const handleDelete = async() => {
    const { cid } = currentOperationItem;
    const messageId = currentOperationItem.msgId || currentOperationItem.id;
    await mySdkStore.sdk.markDingMessageToRecycleBin({ cid, messageId });
    setMessageList(list => list.filter(item => (item.msgId || item.id) !== messageId));
    setMoreOperationVisible(false);
  }

  const handleMarkToRead = async (item) => {
    const { msgId, localMsgId, cid } = item;
    let msgIds;
    if (!msgId) {
      msgIds = messageList.map(({ id }) => ({ msgId: id }));
    } else {
      msgIds = [{ msgId, localMsgId }];
    }
    // todo: 没有全部标记为已读接口
    await mySdkStore.sdk.changeMessagesStatus({ cid, type: 'read', msgIds });
    getNextData(undefined, { changeTab: true });
    setMessageList(list => list.filter(item => item.id !== msgId));
  }

  const toChatDetailPage = (cid, msgId) => {
    history.push({ pathname: `/chatDetail/${cid}`, state: { msgId }});
  }

  const actions = [
    { text: '删除', key: 'delete', onClick: handleDelete },
  ];

  const renderList = () => {
    return <>
      <List style={{ '--border-inner': 0, marginTop: 12 }}>
        {messageList.map(item => {
          const listItem = <List.Item
            key={item.msgId || item.id}
          >
            { !isSendByMe(item.from?.userId) ?
            <div style={{ display: 'flex' }}>
              <AvatarImage
                src={item.from?.avatarUrl}
                nickName={item.from?.nickName}
                userName={item.from?.userName}
                userId={item.from?.userId}
                style={{ borderRadius: 8, display: 'inline-block', marginRight: 11 }}
                fit='cover'
                width={32}
                height={32}
              />
              <div style={{ lineHeight: '32px' }}>{item.from?.nickName}</div>
              { item.readStatus === '0' && <Badge style={{ float: 'right' }} content={Badge.dot}></Badge>}
            </div> :
            <div className="sendBar">
              我发给：
              {/* todo: receivelist缺少NickName */}
              {(item.msgContent || item.content).receivers.map(userId =>
                <span key={userId}>
                  <a style={{ marginRight: 12 }}>{ userId }</a>
                  {/* todo:  缺少是否接收人是否已查收字段*/}
                  {/* <Badge content={<CheckCircleOutline />}><a>{ item.to?.nickName }</a></Badge> */}
                </span>
              )}
            </div>
            }
            {/* <div className="userMessage">{item.msgContent?.content || item.content?.content}</div> */}
            <div className="userMessage" onClick={() => toChatDetailPage(item.cid || item.sid, item.msgId || item.id)}>
              {renderMsgBrief({msgType: (item.msgContent || item.content)?.sourceContentType, messageContent: item.msgContent || item.content})}
            </div>
            {/* todo: 没有找到来自回话字段 */}
            {/* <div className="messageSource">来自会话：张三 <RightOutline /> </div> */}
            <Grid columns={2} className="bottomBar">
              <Grid.Item>
                <span className="time">{ moment(item.timestamp).format('HH:mm') }</span>
              </Grid.Item>
              {/* todo: 没有找到回复字段 */}
              <Grid.Item style={{ textAlign: 'right' }}>
                {/* <MessageOutline /> <Badge content="+1"> 2 </Badge> */}
                <MoreOutline style={{ marginLeft: 16 }} onClick={() => handleMoreOpeationVisible(item)} />
              </Grid.Item>
            </Grid>
          </List.Item>
          return listItem;
          }
        )}
      </List>
      <InfiniteScroll loadMore={() => getNextData(pagination.nextCursorId)} hasMore={hasMore} />
    </>
  }

  return (<div className="strongReminderMessageListPage">
    <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}
      right={<DeleteOutlined style={{ color: 'rgba(0,0,0,0.65)' }} onClick={() => history.push({ pathname: '/StrongReminderRecycleBin' })} />}>
      消息提醒</NavBar>
    <Tabs style={{ '--content-padding': 0 }} onChange={handleChange} className="pageTab">
      <Tabs.Tab title='全部' key='all'>
        {renderList()}
      </Tabs.Tab>
      <Tabs.Tab title='未读' key='unread'>
        {/* { !!messageList.length &&
          <Button size="small" style={{ display: 'block', margin: '12px auto 0', padding: '4px 16px', borderRadius: '20px' }} onClick={() => handleMarkToRead()}>全部标为已读</Button>
        } */}
        {renderList()}
      </Tabs.Tab>
      <Tabs.Tab title='已发出' key='send'>
        {renderList()}
      </Tabs.Tab>
      {/* <Tabs.Tab title='新评论' key='commend'>
        <Button size="small" style={{ display: 'block', margin: '4px auto 16px', padding: '4px 16px', borderRadius: '20px' }}>全部标为已读</Button>
        {list}
      </Tabs.Tab> */}
    </Tabs>
    <ActionSheet
      extra='选择群发方式'
      cancelText='取消'
      visible={moreOperationVisible}
      actions={actions}
      onClose={() => setMoreOperationVisible(false)}
    />
  </div>)
}